package cn.pzh.guli.service.utils;

import com.sun.xml.internal.ws.handler.HandlerException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.util.StringUtils;

import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;


/**
 * 工具类
 * JWT工具
 */
@Slf4j
public class JwtUtil {
    public static final String APP_SECRET="usdiausASDHsahaASKDJ";

    //生成key（加密）
    private static Key getKeyInstance(){
        SignatureAlgorithm signatureAlgorithm=SignatureAlgorithm.HS256;//签名算法
        byte[] bytes= DatatypeConverter.parseBase64Binary(APP_SECRET);
        return new SecretKeySpec(bytes,signatureAlgorithm.getJcaName());
    }
    //获取jwt TOKEN
    public static String getToken(JwtInfo jwtInfo,int expire){
        String JwtToken= Jwts.builder()
                .setHeaderParam("typ","JWT")
                .setHeaderParam("alg","HS256")
                .setSubject("guli-user")//设置主题
                .setIssuedAt(new Date())//颁发时间
                .setExpiration(DateTime.now().plusSeconds(expire).toDate())//过期时间
                .claim("id",jwtInfo.getId())//id
                .claim("nickname",jwtInfo.getNickname())//name
                .claim("avatar",jwtInfo.getAvatar())//头像
                .signWith(SignatureAlgorithm.HS256,getKeyInstance())//签名
                .compact();
        return JwtToken;

    }
    //判断token是否存在或者有效
    public static boolean checkJwtToken(HttpServletRequest request){
        try {
        String jwtToken=request.getHeader("token");
        if (StringUtils.isEmpty(jwtToken)){
            return false;
        }
            Jwts.parser().setSigningKey(getKeyInstance()).parseClaimsJws(jwtToken);
        }
        catch (Exception e){
            return false;
        }
        return true;
    }
    //解析 根据token解析id
    public static JwtInfo getMemberInfoByToken(HttpServletRequest request){
        String jwtToken=request.getHeader("token");
        if (StringUtils.isEmpty(jwtToken)) return null;
        try {

            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(getKeyInstance()).parseClaimsJws(jwtToken);
            Claims claims=claimsJws.getBody();
            JwtInfo jwtInfo=new JwtInfo(claims.get("id").toString(),claims.get("nickname").toString(),claims.get("avatar").toString());
            return jwtInfo;
        }
        catch (Exception e){
             log.info("非法token入侵");
            return null;
        }
    }
}
